package com.xh.bussiness.thirdapi.feihong.service.impl;

import com.aspose.slides.Collections.Specialized.CollectionsUtil;
import com.xh.bussiness.permission.bean.request.UserRequest;
import com.xh.bussiness.permission.model.School;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.service.ISchoolService;
import com.xh.bussiness.thirdapi.feihong.config.FhConfig;
import com.xh.bussiness.thirdapi.feihong.constant.FeihongConstant;
import com.xh.bussiness.thirdapi.feihong.model.FhEmployee;
import com.xh.bussiness.thirdapi.feihong.model.FhGroupSchedule;
import com.xh.bussiness.thirdapi.feihong.model.FhSchedule;
import com.xh.bussiness.thirdapi.feihong.model.FhSchool;
import com.xh.bussiness.thirdapi.feihong.service.IFeihongService;
import com.xh.bussiness.thirdapi.feihong.util.FeiHongMd5Util;
import com.xh.bussiness.thirdapi.feihong.util.JSONPUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author Pitt Cheung
 * @date 2021/6/15 15:36
 */
@Service
public class FeihongServiceImpl implements IFeihongService {

    @Autowired
    private FhConfig fhConfig;
    @Autowired
    private IUserService userService;
    @Autowired
    private ISchoolService schoolService;

    @Override
    public List<FhEmployee> queryTeacherByMobile(String mobile) {
        Map<String, String> paramMap = new HashMap();
        paramMap.put("mobile", StringUtils.isEmpty(mobile) ? "0" : mobile);

        String urlStr = FeiHongMd5Util.geturlstr(paramMap, fhConfig.getAccesskey());
        paramMap.put("accesskey", fhConfig.getAccesskey());
        paramMap.put("sign", FeiHongMd5Util.getmd5sign(urlStr));
        Map map = JSONPUtils.jsonp(paramMap, fhConfig.getHost() + FeihongConstant.QUERY_TEACHER_BY_PHONE);
        Object data = map.get("data");
        if (Objects.nonNull(data)) {
            List<FhEmployee> employees = (List<FhEmployee>) data;
            return employees;
        }
        return null;
    }

    @Override
    public List<FhSchool> querySchool(String provinceId, String cityId, String areaId) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("provinceid", provinceId == null ? "0" : provinceId);
        paramMap.put("cityid", cityId == null ? "0" : cityId);
        paramMap.put("areaid", areaId == null ? "0" : areaId);

        String urlStr = FeiHongMd5Util.geturlstr(paramMap, fhConfig.getAccesskey());
        paramMap.put("accesskey", fhConfig.getAccesskey());
        paramMap.put("sign", FeiHongMd5Util.getmd5sign(urlStr));
        Map map = JSONPUtils.jsonp(paramMap, fhConfig.getHost() + FeihongConstant.QUERY_SCHOOL_BY_AREA);
        Object data = map.get("data");
        if (Objects.nonNull(data)) {
            List<FhSchool> schools = (List<FhSchool>) data;
            return schools;
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> queryAreaByParentId(String provinceId, String cityId, String areaId) {
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("provinceid", StringUtils.isEmpty(provinceId) ? "0" : provinceId);
            paramMap.put("cityid", StringUtils.isEmpty(cityId) ? "0" : cityId);
            paramMap.put("areaid", StringUtils.isEmpty(areaId) ? "0" : areaId);

            String urlStr = FeiHongMd5Util.geturlstr(paramMap, fhConfig.getAccesskey());
            paramMap.put("accesskey", fhConfig.getAccesskey());
            paramMap.put("sign", FeiHongMd5Util.getmd5sign(urlStr));
            Map map = JSONPUtils.jsonp(paramMap, fhConfig.getHost() + FeihongConstant.QUERY_AREA);
            List<Map<String, Object>> data = (List<Map<String, Object>>) map.get("data");
            //区域数据返回了城市需要去掉
            if (!StringUtils.isEmpty(provinceId) && !StringUtils.isEmpty(cityId) && !CollectionUtils.isEmpty(data)) {
                data.remove(0);
            }
            return data;
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public List<FhSchedule> querySchedule(String teacherId, String startDate, String endDate) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("teacherid", StringUtils.isEmpty(teacherId) ? "0" : teacherId);
        paramMap.put("startdate", startDate);
        paramMap.put("enddate", endDate);
        paramMap.put("state", "0");
        paramMap.put("bit_ydy", "0");

        String urlStr = FeiHongMd5Util.geturlstr(paramMap, fhConfig.getAccesskey());
        paramMap.put("accesskey", fhConfig.getAccesskey());
        paramMap.put("sign", FeiHongMd5Util.getmd5sign(urlStr));
        Map map = JSONPUtils.jsonp(paramMap, fhConfig.getHost() + FeihongConstant.QUERY_TEACHER_PAIKE);
        Object data = map.get("data");
        if (Objects.nonNull(data)) {
            List<FhSchedule> schedules = (List<FhSchedule>) data;
            return schedules;
        }
        return null;
    }

    @Override
    public List<FhGroupSchedule> queryGroupSchedule(String teacherId, String startDate, String endDate) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("teacherid", StringUtils.isEmpty(teacherId) ? "0" : teacherId);
        paramMap.put("startdate", StringUtils.isEmpty(startDate) ? "0" : startDate);
        paramMap.put("enddate", StringUtils.isEmpty(endDate) ? "0" : endDate);
        paramMap.put("state", "0");

        String urlStr = FeiHongMd5Util.geturlstr(paramMap, fhConfig.getAccesskey());
        paramMap.put("accesskey", fhConfig.getAccesskey());
        paramMap.put("sign", FeiHongMd5Util.getmd5sign(urlStr));
        Map map = JSONPUtils.jsonp(paramMap, fhConfig.getHost() + FeihongConstant.QUERY_TEACHER_PAIKE_BK);
        Object data = map.get("data");
        if (Objects.nonNull(data)) {
            List<FhGroupSchedule> schedules = (List<FhGroupSchedule>) data;
            for (FhGroupSchedule datum : schedules) {
                datum.setPaikeId(String.format("%s%s%s%s%s", teacherId, datum.getClassId(), datum.getClassDate(), datum.getStartTime(), datum.getEndTime()));
            }
            return schedules;
        }
        return null;
    }

    @Override
    public int importTeacher() {
        List<FhEmployee> fjEmployees = queryTeacherByMobile(null);
        for (int i = 0; i < fjEmployees.size(); i++) {
            FhEmployee fhEmployee = fjEmployees.get(i);

            String mobile = fhEmployee.getMobile();
            // 我们系统里的id是32位的UUID,校管家的是36位
            String employee_id = fhEmployee.getUserId().toString();
            User exists = userService.getById(employee_id);
            if (exists != null) {
                User user = new User();
                user.setId(exists.getId());
                user.setStatus(0);
                user.setUsername(fhEmployee.getUsername());
                user.setNickname(fhEmployee.getRealName());
                user.setMobile(mobile);
                userService.update(user);
            } else {
                UserRequest request = new UserRequest();
                request.setId(employee_id);
                request.setMobile(mobile);
                request.setNickname(fhEmployee.getRealName());
                request.setUsername(fhEmployee.getUsername());
                request.setStatus(0);
                request.setIsFront(1);
                request.setIsAdmin(1);
                request.setSource(3);
                request.setThirdId(fhEmployee.getUserId().toString());
                // 默认 “系统默认” 教师分组
                request.setGroupIds(Collections.singletonList("1"));
                // 默认 “系统默认” 角色
                if (fhEmployee.getType().equals("在职")) {
                    request.setRoleIds(Collections.singletonList("2"));
                } else {
                    request.setRoleIds(Collections.singletonList("3"));
                }
                //校区
                if (!StringUtils.isEmpty(fhEmployee.getSchoolId())) {
                    request.setSchoolIds(Collections.singletonList(fhEmployee.getSchoolId()));
                }
                userService.addUser(request);
            }
        }
        return 0;
    }

    @Override
    public int importSchool() {
        List<Map<String, Object>> maps = queryAreaByParentId(null, null, null);
        if (!CollectionUtils.isEmpty(maps)) {
            for (Map<String, Object> map : maps) {
                List<FhSchool> schools = querySchool(map.get("ID").toString(), null, null);
                for (FhSchool fhSchool : schools) {
                    School school = new School();
                    school.setId(fhSchool.getID());
                    school.setSchoolName(fhSchool.getName());
                    school.setThirdId(fhSchool.getID());
                    schoolService.saveOrUpdate(school);
                }
            }
        }
        return 0;
    }
}
